/* eslint-disable import/no-dynamic-require */
const axios = require('axios');
const ora = require('ora');
const inquirer = require('inquirer');
const { promisify } = require('util');
const path = require('path');
const fs = require('fs');
let downloadGit = require('download-git-repo');

downloadGit = promisify(downloadGit);
const MetalSmith = require('metalsmith');
const { render } = require('consolidate').ejs;
let ncp = require('ncp');

ncp = promisify(ncp);
const { downLoadDirectory } = require('./constants');

const fetchRepoList = async () => {
  const { data } = await axios.get('https://api.github.com/orgs/zhu-cli/repos');
  return data;
};

const waitFnloading = (fn, message) => async (...args) => {
  const spinner = ora(message); spinner.start();
  const result = await fn(...args);
  spinner.succeed();
  return result;
};

const fetchTagList = async (repo) => {
  const { data } = await axios.get(`https://api.github.com/repos/zhu-cli/${repo}/tags`);
  return data;
};

const download = async (repo, tag) => {
  let api = `zhu-cli/${repo}`;
  if (tag) {
    api += `#${tag}`;
  }
  const dest = `${downLoadDirectory}/${repo}`;
  await downloadGit(api, dest);
  return dest;
};

module.exports = async (projectName) => {
  let repos = await waitFnloading(fetchRepoList, 'fetch template ....')();
  repos = repos.map((item) => item.name);

  const { repo } = await inquirer.prompt({
    name: 'repo',
    type: 'list',
    message: 'please choise a template to create project',
    choices: repos,
  });

  let tags = await waitFnloading(fetchTagList, 'fetch tags ....')(repo);
  tags = tags.map((item) => item.name);

  const { tag } = await inquirer.prompt({
    name: 'tag',
    type: 'list',
    message: 'please choise tags to create project',
    choices: tags,
  });
  const result = await waitFnloading(download, 'download template')(repo, tag);

  if (!fs.existsSync(path.join(result, 'ask.js'))) {
    await ncp(result, path.resolve(projectName));
  } else {
    await new Promise((resolve, reject) => {
      MetalSmith(__dirname)
        .source(result)
        .destination(path.resolve(projectName))
        .use(async (files, metal, done) => {
          // eslint-disable-next-line global-require
          const args = require(path.join(result, 'ask.js'));
          const obj = await inquirer.prompt(args);
          const meta = metal.metadata();
          Object.assign(meta, obj);
          delete files['ask.js'];
          done();
        })
        .use((files, metal, done) => {
          const obj = metal.metadata();
          Reflect.ownKeys(files).forEach(async (file) => {
            if (file.includes('js') || file.includes('json')) {
              const content = files[file].contents.toString();
              if (content.includes('<%')) {
                conteny = await render(content, obj);
                files[file].contents = Buffer.from(content);
              }
            }
          });

          done();
        })
        .build((err) => {
          if (err) {
            reject();
          } else {
            resolve();
          }
        });
    });
  }
};
